<template>
  <div class="card" style="width:50%">
    <div style="margin-left:20px; padding:20px 20px; font-size:large; font-weight:bolder;">修改密码</div>
      <el-form ref="formRef" :model="data.user" :rules="data.rules" label-position="right" label-width="80px" padding="20px 30px 20px 0">
        <el-form-item prop="password" label="原密码">
          <el-input v-model="data.user.password" show-password autocomplete="new-password" prefix-icon="Lock" placeholder="请输入原密码"/>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input v-model="data.user.newPassword" show-password autocomplete="new-password" prefix-icon="Lock" placeholder="请输入新密码"/>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input v-model="data.user.confirmPassword" show-password autocomplete="new-password" prefix-icon="Lock" placeholder="请确认新密码"/>
        </el-form-item>
        <div style="text-align: center;">
          <el-button type="primary" style="padding:20px 40px; " @click="save">保存</el-button>
        </div>
      </el-form>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

const validatePass = (rules, value, callback) => {
  //value表示用户输入的确认密码
  if (value !== data.user.newPassword) {
    callback(new Error("两次密码不匹配！"))
  } else {
    callback()
  }
}

const data = reactive({
  user:JSON.parse(localStorage.getItem('code_user') || '{}'),
  rules: {
    password:[
      {required:true, message:'请输入原密码', trigger:"blur"}
    ],
    newPassword:[
      {required:true, message:'请输入新密码', trigger:"blur"},
      {min: 6, message:'密码最少六位', trigger:"blur"}
    ],
    confirmPassword:[
      {required:true, message:'请再次确认密码', trigger:"blur"},
      {validator:validatePass,trigger:"blur"}
    ],
  },
})

const formRef = ref();

const save = () => {
  formRef.value.validate(valid => {
    if (valid) {
      request.post('/updatePassword', data.user).then(res => {
        if (res.code === '200') {
          ElMessage.success('修改成功，请重新登录')
          setInterval(() => {
            localStorage.removeItem('code_user')
            location.href = '/login'
          }, 500)
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
</script>